package v1

import (
	"cheater_zero/pkg/logging"
	"log"
	"net/http"
	"strconv"
	"strings"

	"github.com/gin-gonic/gin"
	"github.com/go-vgo/robotgo"
	"github.com/gorilla/websocket"
)

var upgrader = websocket.Upgrader{
	// 解决跨域问题
	CheckOrigin: func(r *http.Request) bool {
		return true
	},
} // use default options

// WebSocket 构建的劫持指令通道
func HijackComandWS(c *gin.Context) {
	ws, err := upgrader.Upgrade(c.Writer, c.Request, nil)
	if err != nil {
		logging.DefaultLogger.Errorf("%s", err.Error())
		return
	}
	defer ws.Close()
	for {
		_, message, err := ws.ReadMessage()
		if err != nil {
			logging.DefaultLogger.Errorf("从websocket读取hijack command失败, %s", err.Error())
			break
		}

		arr := strings.Fields(string(message))
		switch arr[0] {
		case "mousemove":
			x, _ := strconv.ParseFloat(arr[1], 64)
			y, _ := strconv.ParseFloat(arr[2], 64)
			// 将鼠标移动到屏幕 x y 的位置（模仿人类操作）
			robotgo.MoveMouseSmooth(int(1920*x), int(1080*y), 0.5, 0.5)
		}
	}
}

func CmdWebSocket(c *gin.Context) {
	ws, err := upgrader.Upgrade(c.Writer, c.Request, nil)
	if err != nil {
		log.Print("upgrade:", err)
		return
	}
	defer ws.Close()
	for {
		mt, message, err := ws.ReadMessage()
		if err != nil {
			log.Println("read:", err)
			break
		}
		log.Printf("recv: %s", message)
		err = ws.WriteMessage(mt, message)
		if err != nil {
			log.Println("write:", err)
			break
		}
	}
}
